<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Upload;


class BannerController extends Controller {

    public function bannerAdd(){
        if (!checkCookie()) {
            $this->redirect('Admin/Index/login');
        }
        if (!IS_POST) {
            $this->display();
        }else{
            //接收文件 调用文件上传
            $upload = new \Admin\Controller\MyUploadController();
            $info = $upload->upload();
            if (!$info) {
                $this->ajaxReturn(ajax_data(1,'上传失败'));
            } else {
                $_POST['banner'] = $info['pic'];
                $_POST['ctime'] = time();
            }
            //存储数据
            $bannerModel=M('banner');
            $data = $bannerModel->create();
            if($bannerModel->data($data)->add()){
                $this->ajaxReturn(ajax_data(0,'上传成功'));
            }else{
                $this->ajaxReturn(ajax_data(1,'上传失败'));
            }
        }
    }
    public function bannerList(){
        if (!checkCookie()) {
            $this->redirect('Admin/Index/login');
        }
        $bannerModel = M('banner');
        $banners = $bannerModel->field('bid,title')->where('is_del=0&type=1')->select(); 
        $this->assign('banners',$banners); 
        $this->display();
    }

    public function bannerEdit(){
        if (!checkCookie()) {
            $this->redirect('Admin/Index/login');
        }
        $bannerModel = D('banner');
    	if (!IS_POST) {
            $catModel = D('banner');
            $banner_id = I('get.bid');
            $banner  = $bannerModel->where('bid='.$banner_id)->find(); 
            $this->assign('banner',$banner); 
            $this->display();
    	}else{
            if ($_FILES['pic']['error'] == 0) {
                //接收文件 调用文件上传
                $upload = new \Admin\Controller\MyUploadController();
                $info = $upload->upload();
                if (!$info) {
                    $this->ajaxReturn(ajax_data(1,'上传失败'));
                } else {
                    $_POST['banner'] = $info['pic'];
                }
            }

            //存储数据
            $bannerModel=M('banner');
            $data = $bannerModel->create();

            if($bannerModel->where('bid='.I('get.bid'))->save()){
                $this->ajaxReturn(ajax_data(0,'修改成功'));
            }else{
                $this->ajaxReturn(ajax_data(1,'修改失败'));
            }
        }
    }
    
    public function bannerDel(){
        if (!checkCookie()) {
            $this->redirect('Admin/Index/login');
        }
        $bannerModel = M('banner');
        $bannerModel->is_del = 1;
        $bannerModel->where('bid='.I('get.bid'))->save();
        $this->redirect('admin/banner/bannerList');
    }
}